package com.yang.wfcuser.security;

import com.yang.wfcuser.mapper.UserMapper;
import com.yang.wfcuser.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserLoginInfoVO loginInfoByUsername = userMapper.getLoginInfoByUsername(s);
        if (loginInfoByUsername==null){
            return null;
        }

        List<String> privilege = loginInfoByUsername.getPrivilege();
        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
        for (String permission:privilege) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }


        UserDetails userDetails = new UserDetails(loginInfoByUsername.getId(),
                loginInfoByUsername.getUsername(),
                loginInfoByUsername.getPassword(),
                loginInfoByUsername.getEnable() == 1,
                authorities);
        log.debug("即将向Spring Security返回UserDetails对象：{}", userDetails);
        return userDetails;
    }

}
